import json

from django.conf import settings
from django.urls import reverse
from rest_framework_jwt.utils import jwt_payload_handler

from . import sinaweibopy3
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect
from QQLoginTool.QQtool import OAuthQQ
# Create your views here.
from django.views import View
from meiduo_test.settings.dev import QQ_CLIENT_ID,QQ_CLIENT_SECRET,QQ_REDIRECT_URI, logger
from utils.response_code import RETCODE
from .models import QQlogin, OAuthSinaUser
from apps.users.models import User
from django_redis import get_redis_connection



#获取qq登录页面
class QQAuthURLView(View):
    def get(self,request):
        next = request.GET.get('next')



        oauth=OAuthQQ(client_id=QQ_CLIENT_ID, client_secret=QQ_CLIENT_SECRET, redirect_uri=QQ_REDIRECT_URI, state=next)
        login_url=oauth.get_qq_url()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})

#获取openid
class Oauth_callback(View):
    def get(self,request):
        next=request.GET.get('state')
        code=request.GET.get('code')
        oauth=OAuthQQ(client_id=QQ_CLIENT_ID, client_secret=QQ_CLIENT_SECRET, redirect_uri=QQ_REDIRECT_URI)
        try:
            token=oauth.get_access_token(code)
            openid=oauth.get_open_id(token)
        except:

            return redirect(next)


        #判断是否绑定用户，
        try:
            qquser=QQlogin.objects.get(openid=openid)

            # user=User.objects.get(mobile=qquser.user)


             # 如绑定，则直接登录
            login(request,qquser.user)

            # secret_openid = SecretOauth().dumps({'openid': openid})
            # context = {'openid': secret_openid}
            # return render(request, 'oauth_callback.html', context)
            response=redirect(reverse("contents:index"))

            response.set_cookie('username',qquser.user.username,max_age=3600 * 24 * 15)

            return response
        #如未绑定，如注册过用户，则绑定用户，存到数据库中
        #如未绑定，返回绑定页面
        except:
            context = {'openid': openid}

            return render(request, 'oauth_callback.html', context)
    #未绑定
    def post(self,request):

        mobile=request.POST.get('mobile')
        password=request.POST.get('password')
        img_code=request.POST.get('image_code')
        msg_code=request.POST.get('sms_code')
        openid=request.POST.get('openid')

        sms_redis=get_redis_connection('sms_code')
        try:
            code_redis=sms_redis.get(mobile)
        except:
            context = {'sms_code_errmsg': '验证码错误'}
            return render(request, 'oauth_callback.html', context)

        #如果存在此用户，则绑定
        try:

            user=User.objects.get(mobile=mobile)
            res = user.check_password(password)

        #若果不存在,则注册
        #如未注册，则注册用户,手机号为用户名，其他照常保存,并在qq关联表中保存
        except:
            user=User.objects.create_user(username=mobile,password=password,mobile=mobile)
            QQlogin.objects.create(user=user, openid=openid)
            login(request, user)
            response = redirect(reverse("contents:index"))
            response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
            return response
        if not res:
            context = {'account_errmsg': '密码错误'}
            return render(request, 'oauth_callback.html', context)
        QQlogin.objects.create(user=user, openid=openid)
        login(request, user)
        response = redirect(next)
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


class SinaAuthURLView(View):
    def get(self,request):
        # render(request,'')
        #生成微博登录url
        #导包
        next=request.GET.get('next')
        print(next)
        client = sinaweibopy3.APIClient(
            # app_key： app_key值
            app_key=settings.APP_KEY,
            # app_secret：app_secret 值
            app_secret=settings.APP_SECRET,
            # redirect_uri ： 回调地址
            redirect_uri=settings.REDIRECT_URL
        )
        login_url = client.get_authorize_url()
        return http.JsonResponse({
            "code":0,
            "errmsg":'提示信息',
            "login_url":login_url,
            })

#微博登录后返回的页面
class Sina_callback(View):
    def get(self,request):
        code=request.GET.get('code')
        # if not code:
        #     return redirect(reverse('contents:login'))
        client = sinaweibopy3.APIClient(
            # app_key： app_key值
            app_key=settings.APP_KEY,
            # app_secret：app_secret 值
            app_secret=settings.APP_SECRET,
            # redirect_uri ： 回调地址
            redirect_uri=settings.REDIRECT_URL
        )
        try:

            token=client.request_access_token(code)
            uid=token.uid
        except:
            print('token失效')
            return redirect(reverse('contents:login'))
        try:
            user=OAuthSinaUser.objects.get(uid=uid).user
            login(request,user)
            response = redirect(reverse("contents:index"))

            response.set_cookie('username',user.username, max_age=3600 * 24 * 15)

            return response
        except:

            return render(request, 'sina_callback.html', context={'uid': uid})

#校验验证码
class SinaUser(View):
    def post(self,request):
        """
        mobile	string	是	手机号
        password	string	是	密码
        sms_code	string	是	验证码
        uid	string	是	绑定的uid
        :param request:
        :return:
        """
        data=json.loads(request.body.decode())
        password=data.get('password')
        sms_code=data.get('sms_code')
        uid=data.get('uid')
        mobile = data.get('mobile')
        print(data)


        # if not uid:
        #     return render(request, 'sina_callback.html', {'uid_errmsg': '无效的uid'})


        redis_client=get_redis_connection('sms_code')
        data=redis_client.get(mobile)
        if not data:
            return render(request, 'sina_callback.html', {'sms_code_errmsg': '无效的短信验证码'})
        if data.decode() !=sms_code:

            return render(request, 'sina_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})

        try:

            user=User.objects.get(mobile=mobile)

            res = user.check_password(password)

            if not res:

                return render(request, 'sina_callback.html', {'account_errmsg': '用户名或密码错误'})


        except:

            user=User.objects.create_user(username=mobile,password=password,mobile=mobile)

        sinar=OAuthSinaUser.objects.create(uid=uid, user_id=user.id)
        login(request, sinar.user)

        response = http.JsonResponse({'status':5000})

        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response




